package org.ms.springcloud.eureka.provider;

import org.ms.springcloud.service.api.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 注册中心客户端
 *
 * @author lry
 */
@RestController
public class RegistryController {

    @Value("${server.port}")
    private String port;

    @Autowired
    private DiscoveryClient discoveryClient;

    /**
     * 获取本地服务实例
     *
     * @return
     */
    @RequestMapping("/local-service-instance")
    public ServiceInstance getLocalServiceInstance() {
        return discoveryClient.getLocalServiceInstance();
    }

    /**
     * 获取指定服务或应用名称下的所有服务实例清单
     *
     * @param serviceName
     * @return
     */
    @RequestMapping("/service-instances/{serviceName}")
    public List<ServiceInstance> serviceInstancesByApplicationName(@PathVariable("serviceName") String serviceName) {
        return this.discoveryClient.getInstances(serviceName);
    }

    /**
     * 获取注册中心所有服务清单
     *
     * @return
     */
    @RequestMapping("/services")
    public List<String> services() {
        return this.discoveryClient.getServices();
    }

    @RequestMapping("/server-info")
    public String serverInfo() {
        return "The server port is " + port;
    }

    @RequestMapping("/user/{id}")
    public User user(@PathVariable("id") Long id) {
        Map<Long, User> users = new HashMap<>();
        users.put(1001L, new User(1001L, "zhangsan", "123456", 23));
        users.put(1002L, new User(1002L, "lisi", "111111", 32));
        users.put(1003L, new User(1003L, "wangwu", "444444", 54));
        return users.get(id);
    }

}